/**   
* @Title: PBLearn.java
* @Package com.an.protocolbuf
* @Description: TODO(用一句话描述该文件做什么)
* @author antch,861710865@qq.com   
* @date 2017年8月3日 下午8:32:57
* @version V1.0   
*/


package com.an.protocolbuf;

import java.util.Arrays;

import com.an.protocolbuf.Chat.Hello;
import com.an.protocolbuf.players.player;
import com.an.protocolbuf.players.player.Builder;
import com.google.protobuf.InvalidProtocolBufferException;

import io.netty.util.CharsetUtil;

/**
* @ClassName: PBLearn
* @Description: TODO(ProtocolBuf學習)
* @author antch,861710865@qq.com
* @date 2017年8月3日 下午8:32:57
* 
*/

public class PBLearn {

	/** 
	* @Title: main 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param args    设定文件 
	* @return void    返回类型 
	* @throws 
	*/

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		byte[] b = new PBLearn().toBytes();
		
		try {
			System.out.println("反序列化：：" + toPlayer(b));
		} catch (InvalidProtocolBufferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println("---------------------------------------");
		byte[] bs = toChatBytes();
		System.out.println("序列化：：" + Arrays.toString(bs));
		Hello h = fromBytes(bs);
	
		System.out.println("反序列化::" + fromBytes(bs));
		
		System.out.println("真正的姓名：：" + new String(h.getName().getBytes(CharsetUtil.UTF_8)));
		
	}

	public byte[] toBytes() {
		Builder builder = players.player.newBuilder();
		
		builder.setAge(20).setName("123").setPlayerId(1568);
		
		player p = builder.build();
		
		//xuelihua
		byte[] b = p.toByteArray();
		System.out.println("序列化后：：" + Arrays.toString(b));
		return b;
		
	}
	
	/**
	 * 反序列化
	 * @throws InvalidProtocolBufferException 
	 */
	
	public static player toPlayer(byte[] b) throws InvalidProtocolBufferException {
		player p = players.player.parseFrom(b);
		return p;
	}
	
	
	public static byte[] toChatBytes() {
		com.an.protocolbuf.Chat.Hello.Builder builder = Chat.Hello.newBuilder();
		builder.setId(123).setName("bciuebviuerbv安天池").setSex(0);
		Hello h = builder.build();
		
		return h.toByteArray();
	}
	
	public static Hello fromBytes(byte[] b) {
		try {
			return Hello.parseFrom(b);
		} catch (InvalidProtocolBufferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
